from typing import Optional
from fastapi import Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from jose import JWTError, jwt
from database import get_db
from models import User
from utils import decode_access_token

# OAuth2密码Bearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")


def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
    """获取当前用户"""
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无法验证凭据",
        headers={"WWW-Authenticate": "Bearer"},
    )
    
    payload = decode_access_token(token)
    if payload is None:
        raise credentials_exception
    
    username: str = payload.get("sub")
    if username is None:
        raise credentials_exception
    
    user = db.query(User).filter(User.username == username).first()
    if user is None:
        raise credentials_exception
    
    if user.status != "1":
        raise HTTPException(status_code=400, detail="用户未激活")
    
    return user


def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
    """获取当前活跃用户"""
    # 由于在get_current_user中已经检查了状态，这里可以省略重复检查
    return current_user


def get_current_superuser(current_user: User = Depends(get_current_active_user)) -> User:
    """获取当前超级用户"""
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="权限不足，需要超级用户权限"
        )
    return current_user


def has_permission(current_user: User, permission_name: str) -> bool:
    """检查用户是否有权限"""
    # 超级用户拥有所有权限
    if current_user.is_superuser:
        return True
    
    # 检查用户角色的权限
    for role in current_user.roles:
        for permission in role.permissions:
            if permission.name == permission_name:
                return True
    
    return False

def has_role_level(current_user: User, required_level: int) -> bool:
    """检查用户是否具有指定级别的角色"""
    # 超级用户拥有所有权限
    if current_user.is_superuser:
        return True
    
    # 检查用户是否拥有等于或高于要求级别的角色
    for role in current_user.roles:
        if role.level >= required_level:
            return True
    
    return False

def get_current_user_with_level(required_level: int):
    """获取具有指定级别角色的当前用户"""
    def get_user(current_user: User = Depends(get_current_active_user)):
        if not has_role_level(current_user, required_level):
            raise HTTPException(
                status_code=403,
                detail="权限不足"
            )
        return current_user
    return get_user

def get_client_ip(request: Request) -> str:
    """
    获取客户端IP地址
    
    优先从X-Forwarded-For头获取，如果没有则使用客户端地址
    """
    x_forwarded_for = request.headers.get("X-Forwarded-For")
    if x_forwarded_for:
        # X-Forwarded-For可能包含多个IP地址，取第一个
        return x_forwarded_for.split(",")[0].strip()
    return request.client.host if request.client else "unknown"